package com.example.bitmapload;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

public class ImageLoad {
	private static ImageLoad obj;
	private HashMap<String,SoftReference<BitmapDrawable>> imageCache;
	public static String folder_cache = Environment.getExternalStorageDirectory()
			+"/Android/data/NetImageDemo/cache/";
	
	//初始化hashmap和sd卡缓存文件
	private ImageLoad(){
		imageCache = new HashMap<String, SoftReference<BitmapDrawable>>();
		File folder = new File(folder_cache);
        if (!folder.exists()) {
            folder.mkdirs();
            try {
                new File(folder, ".nomedia").createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
	}
	
	public static ImageLoad getInstance() {
        if (obj == null)
            obj = new ImageLoad();
        return obj;
    }
	
	//回调接口
	public interface ivCallback{
		public void getImage(BitmapDrawable imageDrawable, String imageUrl);
		public void setImage(BitmapDrawable imageDrawable, String imageUrl);
	}

	//加载图片
	public boolean loadIv(final String url, ImageView imageView, final ivCallback ivCallback) {
		//从缓存中取
		if(imageCache.containsKey(url)){
			SoftReference<BitmapDrawable> softReference = imageCache.get(url);
			BitmapDrawable drawable = softReference.get();
			if (drawable != null) {
				imageView.setImageDrawable(drawable);
                ivCallback.setImage(drawable, url);
                return true;
			}
		}
		//从sd卡中取
		if(new File(folder_cache+url.hashCode()).exists()){
			BitmapDrawable drawable = (BitmapDrawable)BitmapDrawable.
					createFromPath(folder_cache+url.hashCode());
			imageCache.put(url, new SoftReference<BitmapDrawable> (drawable));
			imageView.setImageDrawable(drawable);
			ivCallback.setImage(drawable, url);
            return true;
		}
		//网络上加载
		final Handler handler = new Handler() {
            public void handleMessage(Message message) {
            	ivCallback.getImage((BitmapDrawable) message.obj, url);
            	ivCallback.setImage((BitmapDrawable) message.obj, url);
            }
        };
		
		new Thread(){
			public void run(){
				BitmapDrawable drawable = loadImageFromUrl(url);
                if (drawable == null)
                    return;
                //加载到缓存
                imageCache.put(url, new SoftReference<BitmapDrawable>(drawable));
                Log.i("url", "drawable");
                //加载到SD卡
                new Thread(new WriteToSdcard(drawable, url)).start();
                Message message = handler.obtainMessage(0, drawable);
                handler.sendMessage(message);
			}
		}.start();
		return false;
	}
	
	//写入sd卡
	public class WriteToSdcard implements Runnable {
        private BitmapDrawable drawable;
        private String url;

        public WriteToSdcard(BitmapDrawable drawable, String url) {
            this.drawable = drawable;
            this.url = url;
        }

        @Override
        public void run() {
            try {
                FileOutputStream fw = new FileOutputStream(folder_cache + url.hashCode());
                BufferedOutputStream out = new BufferedOutputStream(fw);
                drawable.getBitmap().compress(Bitmap.CompressFormat.JPEG, 80, out);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
	
	protected static BitmapDrawable loadImageFromUrl(String url) {
		if(url == null)return null;
		URL path;
		InputStream inputStream = null;
		BitmapDrawable drawable = null;
		try {
			path = new URL(url);
			inputStream = (InputStream) path.getContent();
            drawable = (BitmapDrawable) Drawable.createFromStream(inputStream, "src");
            Log.i("net", drawable.toString());
        } catch (MalformedURLException e1) {
             e1.printStackTrace();
        } catch (IOException e) {
             e.printStackTrace();
        }
		return drawable;
	}

}
